package com.example.demo.service;

import com.example.demo.entity.Member;
import com.example.demo.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 会员服务类
 */
@Service
@Transactional
public class MemberService {
    
    @Autowired
    private MemberRepository memberRepository;
    
    public Member save(Member member) {
        return memberRepository.save(member);
    }
    
    public Optional<Member> findById(Long id) {
        return memberRepository.findById(id);
    }
    
    public Optional<Member> findByMemberCode(String memberCode) {
        return memberRepository.findByMemberCode(memberCode);
    }
    
    public Optional<Member> findByPhone(String phone) {
        return memberRepository.findByPhone(phone);
    }
    
    public Optional<Member> findByEmail(String email) {
        return memberRepository.findByEmail(email);
    }
    
    public List<Member> findAll() {
        return memberRepository.findAll();
    }
    
    public List<Member> findByMemberLevel(Member.MemberLevel memberLevel) {
        return memberRepository.findByMemberLevel(memberLevel);
    }
    
    public List<Member> findByStatus(Member.MemberStatus status) {
        return memberRepository.findByStatus(status);
    }
    
    public List<Member> findByKeyword(String keyword) {
        return memberRepository.findByKeyword(keyword);
    }
    
    public List<Member> findByMinPoints(Integer minPoints) {
        return memberRepository.findByMinPoints(minPoints);
    }
    
    public boolean existsByMemberCode(String memberCode) {
        return memberRepository.existsByMemberCode(memberCode);
    }
    
    public boolean existsByPhone(String phone) {
        return memberRepository.existsByPhone(phone);
    }
    
    public boolean existsByEmail(String email) {
        return memberRepository.existsByEmail(email);
    }
    
    /**
     * 注册会员
     */
    public Member registerMember(Member member) {
        // 生成会员编码
        String memberCode = generateMemberCode();
        member.setMemberCode(memberCode);
        member.setRegisterDate(LocalDate.now());
        member.setTotalPoints(0);
        member.setAvailablePoints(0);
        member.setTotalConsumption(BigDecimal.ZERO);
        member.setStatus(Member.MemberStatus.ACTIVE);
        member.setMemberLevel(Member.MemberLevel.BRONZE);
        
        return memberRepository.save(member);
    }
    
    /**
     * 更新会员积分
     */
    public Member updatePoints(Long memberId, Integer points) {
        Optional<Member> memberOpt = findById(memberId);
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("会员不存在");
        }
        
        Member member = memberOpt.get();
        member.setTotalPoints(member.getTotalPoints() + points);
        member.setAvailablePoints(member.getAvailablePoints() + points);
        
        // 更新会员等级
        updateMemberLevel(member);
        
        return memberRepository.save(member);
    }
    
    /**
     * 消费积分
     */
    public Member consumePoints(Long memberId, Integer points) {
        Optional<Member> memberOpt = findById(memberId);
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("会员不存在");
        }
        
        Member member = memberOpt.get();
        if (member.getAvailablePoints() < points) {
            throw new RuntimeException("积分不足");
        }
        
        member.setAvailablePoints(member.getAvailablePoints() - points);
        return memberRepository.save(member);
    }
    
    /**
     * 更新消费金额
     */
    public Member updateConsumption(Long memberId, BigDecimal amount) {
        Optional<Member> memberOpt = findById(memberId);
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("会员不存在");
        }
        
        Member member = memberOpt.get();
        member.setTotalConsumption(member.getTotalConsumption().add(amount));
        member.setLastVisitDate(LocalDate.now());
        
        // 根据消费金额计算积分（1元=1积分）
        Integer points = amount.intValue();
        member.setTotalPoints(member.getTotalPoints() + points);
        member.setAvailablePoints(member.getAvailablePoints() + points);
        
        // 更新会员等级
        updateMemberLevel(member);
        
        return memberRepository.save(member);
    }
    
    /**
     * 更新会员等级
     */
    private void updateMemberLevel(Member member) {
        BigDecimal consumption = member.getTotalConsumption();
        
        if (consumption.compareTo(new BigDecimal("10000")) >= 0) {
            member.setMemberLevel(Member.MemberLevel.DIAMOND);
        } else if (consumption.compareTo(new BigDecimal("5000")) >= 0) {
            member.setMemberLevel(Member.MemberLevel.PLATINUM);
        } else if (consumption.compareTo(new BigDecimal("2000")) >= 0) {
            member.setMemberLevel(Member.MemberLevel.GOLD);
        } else if (consumption.compareTo(new BigDecimal("500")) >= 0) {
            member.setMemberLevel(Member.MemberLevel.SILVER);
        } else {
            member.setMemberLevel(Member.MemberLevel.BRONZE);
        }
    }
    
    /**
     * 生成会员编码
     */
    private String generateMemberCode() {
        return "M" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4).toUpperCase();
    }
    
    public void deleteById(Long id) {
        memberRepository.deleteById(id);
    }
    
    public Member update(Member member) {
        return memberRepository.save(member);
    }
}
